<?php
    /**
     * Created by PhpStorm.
     * 版权所有: 2019~2022 [ hhygyl ]
     * Date: 2019/7/4-11:08
     * Link: http://luckyadmin.luckyhhy.cn
     * FileName: Setting.php
     * Keys: ctrl+alt+L/ctrl+s(代码格式化) ctrl+J(代码提示) ctrl+R(替换)ALT+INSERT(生成代码(如GET,SET方法,构造函数等) , 光标在类中才生效)
     * CTRL+ALT+O (优化导入的类和包 需要配置) SHIFT+F2(高亮错误或警告快速定位错误)
     * CTRL+SHIFT+Z(代码向前) CTRL+SHIFT+/ (块状注释) ctrl+shift+enter(智能完善代码 如if())
     *
     **************************************************************
     *                                                            *
     *   .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-.       *
     *    |                     ______                     |      *
     *    |                  .-"      "-.                  |      *
     *    |                 /            \                 |      *
     *    |     _          |              |          _     |      *
     *    |    ( \         |,  .-.  .-.  ,|         / )    |      *
     *    |     > "=._     | )(__/  \__)( |     _.=" <     |      *
     *    |    (_/"=._"=._ |/     /\     \| _.="_.="\_)    |      *
     *    |           "=._"(_     ^^     _)"_.="           |      *
     *    |               "=\__|IIIIII|__/="               |      *
     *    |              _.="| \IIIIII/ |"=._              |      *
     *    |    _     _.="_.="\          /"=._"=._     _    |      *
     *    |   ( \_.="_.="     `--------`     "=._"=._/ )   |      *
     *    |    > _.="                            "=._ <    |      *
     *    |   (_/                                    \_)   |      *
     *    |                                                |      *
     *    '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-='      *
     *                                                            *
     *                    JUST FIND YOUR BUG !                    *
     **************************************************************
     */

    namespace app\admin\controller;

    use app\admin\model\Upload;
    use app\admin\validate\Aadmimember;
    use service\TreeService;
    use service\UtilService;
    use think\Exception;
    use think\Request;
    use think\Validate;

    class Setting extends SystemBase
    {

        protected $admin_member_model;
        protected $admin_role;
        protected $setting;

        protected function _initialize()
        {
            parent::_initialize(); // TODO: Change the autogenerated stub
            $this->admin_member_model = new \app\admin\model\AdminMember();//后台管理员
            $this->admin_role         = new \app\admin\model\AdminRole();//角色模型
            $this->setting            = db("setting");
        }

        /**
         * @return mixed
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: MyInfo
         * @describe:我的基本资料
         */
        public function MyInfo()
        {
            if($this->request->isAjax()) {
                $data = $this->request->post();
                //dump($data);die;
                try {
                    $valdata = new Aadmimember();//实例化验证器
                    //验证数据合法性
                    if(!$valdata->check($data)) {
                        $this->error('提交失败：'.$valdata->getError());
                    }

                    $res = $this->admin_member_model->addEditData($data);//编辑数据

                    if($res!==false) {
                        $this->AddLogs('修改我的基本资料');

                         $this->success("修改成功");
                    }
                    else {
                         $this->error("修改失败");
                    }
                } catch (Exception $exception) { //捕获异常
                     $this->error($exception->getMessage());
                }
            }
            $info= $this->admin_member_model->get(self::$admin_ID); //

            $tree = TreeService::toFormatTree($this->admin_role->GetRoleList(), "name");//获取角色
            $this->assign(compact("tree","info"));
            return $this->fetch();
        }



        /**
         * @return mixed
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: MyPass
         * @describe:修改我的密码
         */
        public function MyPass()
        {
            if($this->request->isAjax()) {
                $data     = $this->request->post();
                $validate = new Validate([['oldpassword|token', 'alphaNum', '密码只允许字母、数字'], ['password', 'min:6|max:16|alphaNum', '密码最少6个字符|密码最长16个字符|密码只允许字母、数字'], ['repassword', 'confirm:password', '两次密码输入不一致'],]);

                //校验数据
                if(!$validate->check($data)) {
                    $this->error($validate->getError());
                }

                $pass = UtilService::think_decrypt(self::$admin_info['password']);
                if($pass!=$data['oldpassword']) {
                    $this->error("当前密码输入错误");
                }


                $data['password']=UtilService::think_encrypt($data['password']);

                unset($data['oldpassword']);
                unset($data['repassword']);



                $res = $this->admin_member_model->addEditData($data);//编辑数据

                if($res!==false) {
                    $this->AddLogs('修改我的密码');

                     $this->success("修改成功");
                }
                else {
                     $this->error("修改失败");
                }
            }

            return $this->fetch();
        }



        /**
         * @return mixed
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: site
         * @describe:网站设置
         */
        public function site()
        {
            if($this->request->isAjax()) {
                $data = $this->request->post();
                foreach($data as $k => $v){
                    $res = $this->setting->where("key", $k)->setField("value", $v);
                }
                $this->AddLogs('设置网站信息');

                $this->success("提交成功");
            }
            $this->assign("info", self::$setting_config);
            return $this->fetch();
        }


        /**
         * @return mixed
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: safe
         * @describe:安全设置
         */
        public function safe()
        {
            if($this->request->isAjax()) {
                $data = $this->request->post();
                $res  = $this->setting->where("key", "safe")->setField("value", json_encode($data['safe']));
                //dump($data);
                $this->AddLogs('网站安全设置');

                $res ? $this->success("提交成功") : $this->error("提交失敗");
            }

            // dump(self::$setting_config);
            $this->assign("safe", self::$setting_config['safe']);
            return $this->fetch();
        }



        /**
         * @return mixed
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: email
         * @describe:邮箱设置
         */
        public function email()
        {
            if($this->request->isPost()) {
                $post = $this->request->post();
                // dump($post);die;
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new Validate([['from_email', 'require|email', '发件箱不能为空|发件箱格式不正确'], ['from_name', 'require', '发件人不能为空'], ['smtp', 'require', '邮箱smtp服务器不能为空'], ['username', 'require|email', '登录账户不能为空|登录账户应为邮箱格式'], ['password', 'require', '登录密码不能为空'], ['content', 'require', '邮件模板不能为空'],]);
                //验证部分数据合法性
                if(!$validate->check($post['email'])) {
                    $this->error('提交失败：'.$validate->getError());
                }

                $data = json_encode($post['email']);
                $res  = \app\admin\model\Setting::update(['value' => $data], ['key' => 'email']);
                if($res==false) {

                    $this->AddLogs('邮箱设置');

                    $this->error("修改失败");
                }
                else {
                    $this->success("修改成功");
                }
            }

            /*  $s=new \app\admin\model\Setting();
              dump($s->getSetting());*/
            $res = db("setting")->where("key", "email")->find();
            //dump(json_decode($res['value']));
            $this->assign("info", json_decode($res['value']));
            return $this->fetch();
        }


        /**
         * @return mixed|void
         * @throws \phpmailerException
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: hhygyl <hhygyl520@qq.com>
         * @name: mailto
         * @describe:发送邮件测试
         */
        public function mailto()
        {
            if($this->request->isPost()) {
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new Validate([['email', 'require|email', '收件箱不能为空|收件箱格式不正确'],]);
                //验证部分数据合法性
                if(!$validate->check($post)) {
                    $this->error('提交失败：'.$validate->getError());
                }

                $address = $post['email'];
                $mailto  = SendMail($address);
                if(false==$mailto) {
                     $this->error('发送失败');
                }
                else {
                    $this->AddLogs('发送邮件测试【'.$post['email'].'】');

                     $this->success('邮件发送成功');
                }
            }
            else {
                return $this->fetch();
            }
        }


        /**
         * @param $address
         * @param $title
         * @param $fromname
         * @param $message
         * @return array
         * @throws \phpmailerException
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: SendMails
         * @describe:发送邮件
         */
       public function SendMails($address,$title,$fromname,$message)
        {
            vendor('phpmailer.PHPMailerAutoload');
            $mail = new \PHPMailer();
            // 设置PHPMailer使用SMTP服务器发送Email
            $mail->IsSMTP();
            // 设置邮件的字符编码，若不指定，则为'UTF-8'
            $mail->CharSet='UTF-8';
            // 添加收件人地址，可以多次使用来添加多个收件人
            $mail->AddAddress($address);
            $data=db("setting")->where("key","email")->find();
            $data=json_decode($data["value"]);
            $from = $data->from_email;
            $smtp = $data->smtp;
            $username = $data->username;
            $password = $data->password;
            // 设置邮件正文
            $mail->Body=$message;
            // 设置邮件头的From字段。
            $mail->From=$from;
            // 设置发件人名字
            $mail->FromName=$fromname;
            // 设置邮件标题
            $mail->Subject=$title;
            // 设置SMTP服务器。
            $mail->Host=$smtp;
            // 设置使用ssl加密方式登录鉴权
            $mail->SMTPSecure = 'ssl';
            // 设置ssl连接smtp服务器的远程服务器端口号
            $mail->Port = 465;
            // 设置为"需要验证" ThinkPHP 的config方法读取配置文件
            $mail->SMTPAuth=true;
            //设置html发送格式
            $mail->isHTML(true);
            // 设置用户名和密码。
            $mail->Username=$username;
            $mail->Password=$password;
            try{
                $ok=$mail->Send();
                if($ok){
                    return ['code'=>1,'msg'=>'发送成功'];
                }else{
                    return ['code'=>0,'msg'=>$mail->ErrorInfo];
                }
            }catch (Exception $exception){
                return ['code'=>0,'msg'=>$exception->getMessage()];
            }

        }

        /**
         * @param Request $request
         * @throws \phpmailerException
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: send_post
         * @describe:提交数据
         */
        public function send_post(Request $request){
            if ($request->isPost()){
                //邮箱验证表达式
                $regex="/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
                $data=$_POST;
                $adre=@explode(",",$data['maile']);
                //去除空值
                $cont=$this->array_remove_empty($adre);
                if (count($cont) >1){
                    $arr=[];
                    foreach ($cont as $v){
                        //验证邮箱
                        $result = preg_match($regex,$v);
                        if (!$result){
                            unset($v);
                        }else{
                            $arr[]=$v;
                        }
                    }
                    $address=$arr;
                }else{
                    $result = preg_match($regex,$cont[0]);
                    if (!$result){
                        $this->error("接收人邮箱有误");
                    }
                    $address=$cont[0];
                }
                //发送邮件
                $i=0;
                foreach($address as $k=>$v){
                      $res=$this->SendMails($v,$data['subject'],$data['nickname'],$data['content']);
                      if($res['code']==1){
                          $i++;
                      }
                      db("email_sends")->insert([
                         'email'=>$v,
                         'title'=>$data['subject'],
                         'content'=>$data['content'],
                         'nickname' =>$data['nickname'],
                          'ok'=>$res['msg'],
                          'create_time'=>date("Y-m-d H:i:s",time())
                      ]);
                }

                $this->success("共发送成功数据【".$i."】条：失败【".count($address)-$i."】条");
            }
        }


        /**
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: sends
         * @describe:获取数据
         */
        public function sends(){
            if($this->request->isAjax()) {
                return GetPageData([], "email_sends");
            }
        }


        /**
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: email_delete
         * @describe:删除邮件发送记录
         */
        public function email_delete(){
            if($this->request->isAjax()){
                $ids = $this->request->post("ids");
                return $this->DeleteData("email_sends",$ids);
            }
        }

        /**
         * @return array
         * @throws \PHPExcel_Exception
         * @throws \PHPExcel_Reader_Exception
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: upfile
         * @describe:上传文件
         */
        public function upfile(){
            $res=model("Upload")->upfile("file");
            if($res['code']==1){

                if ($res['ext']=='txt'){
                    $str=$this->getTxtcontent($res['path']);
                    if (isset($str['code'])){
                        return array('code'=>0,'msg'=>$str['msg']);
                    }else{
                        return array('code'=>1,'msg'=>'数据获取成功','path'=>$res['path'],'str'=>$str);
                    }
                }else{
                    $str=$this->excelImport($res['path']);
                    return array('code'=>200,'msg'=>'导入成功','path'=>$res['path'],'str'=>$str);
                }
            }else{
                $this->error("文件上传失败");
            }
        }


        /**
         * @param $txtfile
         * @return array|string
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: getTxtcontent
         * @describe:获取txt内容
         */
        private function getTxtcontent($txtfile){
            $file = @fopen(ROOT_PATH.$txtfile,'r');
            $content = array();
            if(!$file){
                return ['code'=>0,'msg'=>'文件读取失败'];
            }else{
                $i = 0;
                while (!feof($file)){
                    $content[$i] = mb_convert_encoding(fgets($file),"UTF-8","GBK,ASCII,ANSI,UTF-8");
                    $i++ ;
                }
                fclose($file);
                $content = $this->array_remove_empty($content); //数组去空
            }
            $str=@implode(",",$content);
            return $str;
        }


        /**
         * @param $arr
         * @param bool $trim
         * @return array|bool
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: array_remove_empty
         * @describe:数组去空值
         */
        private function array_remove_empty(&$arr, $trim = true) {
            if (!is_array($arr)) return false;
            foreach($arr as $key => $value){
                if (is_array($value)) {
                    self::array_remove_empty($arr[$key]);
                } else {
                    $value = ($trim == true) ? trim($value) : $value;
                    if (empty($value) || $value=="") {
                        unset($arr[$key]);
                    } else {
                        $arr[$key] = $value;
                    }
                }
            }
            return $arr;
        }


        /**
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: download
         * @describe:模板文件下载
         */
        public function download(){
            $file_name="模板文件.xlsx";
            $file_path=ROOT_PATH.'public/tmpl/muban.xlsx';;
            if(!file_exists($file_path)){
                $this->error("文件不存在");exit;
            }
            $file1=fopen($file_path,"r");
            Header("Content-type: application/octet-stream;charset=utf-8");
            Header("Accept-Ranges: bytes");
            header("Content-Length: " . filesize($file_path));//文件大小
            header('Content-Disposition:attachment;filename="'.$file_name.'"');
            ob_clean();
            flush();
            echo fread($file1,filesize($file_path)); //输出文件大小到浏览器
            fclose($file1);
            exit();
        }


        /**
         * @param $filename
         * @return string
         * @throws \PHPExcel_Exception
         * @throws \PHPExcel_Reader_Exception
         * @author: hhygyl <jackhhy520@qq.com>
         * @name: excelImport
         * @describe:获取excel文件数据
         */
        public function excelImport($filename){
            header("Content-type: text/html; charset=utf-8");
            vendor('phpoffice.phpexcel.Classess');
            $objPHPExcel = \PHPExcel_IOFactory::load(ROOT_PATH.$filename);
            $objWorksheet = $objPHPExcel->getSheet(0);
            $highestRow    = $objWorksheet->getHighestRow();          // 取得总行数
            $highestColumn = $objWorksheet->getHighestColumn();    // 取得总列数
            $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString ( $highestColumn );
            $excelData = array ();
            for($row = 2 ; $row <= $highestRow; $row++) {
                for($col = 0; $col < $highestColumnIndex; $col++) {
                    $excelData[$row-2][] = $objWorksheet->getCellByColumnAndRow( $col, $row )->getValue();
                }
            }
            foreach ($excelData as $k=>$v){
                $ar[]=$v[0];
            }
            $str=@implode(",",$ar);
            return $str;
        }


    }